<?php 

import('@.com.99ebc.lib.Error');
import('@.com.99ebc.lib.File');
import('@.com.99ebc.lib.Xml');

import("ORG.Util.Image");

class UserModel extends Model {
    //表字段配置
    protected $fields   = array(
                                'user_id',
                                'user_name',
                                'user_password',
                                'sort_loc',
                                'user_desc',
                                'image_path',
                                'edit_time',
                                '_pk' => 'user_id',
                                '_autoinc' => true
                            );
    
    //自动验证
    protected $_validate    = array(
        array('user_name', 'require', '姓名不能为空！'),
        array('user_name', '', '用户已存在！请另换一个。', 0, 'unique', 1),
        array('sort_loc', 'number', '排序编号必须是数字！',2),
        array('user_password', 'repassword', '两次密码不一致！',0, 'confirm')
    );

    //自动完成
    protected $_auto        = array(
        array('edit_time', 'mktime', 3, 'function'),
        array('user_password', 'md5', 3, 'function')
    );

    protected static $orderFields = 'sort_loc';

    protected $_imageTypes;
    protected $_imageSize;
    protected $_uploadDir;

    protected $_countWhere;

    protected $_error;

    //默认详细信息里显示的图片类型
    protected static $infoImgType     = '_s';
    //格式:width, height, type, interlace, 后缀
    protected static $thumbImgInfo  = array(
        '_s' => array('w' => 100, 'h' => 100, 't' => 'jpg', 'i' => true),
    );

    public function __construct() {
        parent::__construct();

        $this->_countWhere  = '';
        $this->_imageSize   = 2;
        $this->_imageTypes  = array('jpg', 'jpeg', 'png', 'gif', 'bmp');
        $this->_uploadDir   = 'Public/default/uploadfiles/user';
        $this->_error       = new Error(); 
    }

    //得到记录总数
    public function getCountRecords() {
        return $this->where($this->_countWhere)->count();
    }
    
    //搜索方法
    public function searchUser($page = 0, $keyword, $perPage = 10) {
        if(preg_match('/^\/+\d+$/', $keyword)) {
            $whereSearch  = '`user_id` = ' . strtr($keyword, array('/' => ''));
        } else {
            $whereSearch  = '`user_name` like \'%' . $keyword . '%\'';
        }
        $this->_countWhere  = $whereSearch;

        return $this->seeUser($page, $whereSearch, $perPage);
    }

    //查看列表方法 
    public function seeUser($page = 0, $whereIndex = '', $perPage = 10) {
        return $this->where($whereUser)->order('sort_loc')->limit($perPage)->page($page)->select();
    }

    //查看记录详细信息方法
    public function infoUser($recordId) {
        $record     = $this->where('`user_id` = ' . $recordId)->find();
        if(!empty($record['image_path'])) {
            $record['image_path_small']     = $this->genThumbImageName($record['image_path']) . self::$infoImgType . '.' . self::$thumbImgInfo[self::$infoImgType]['t']; 
        }
        return $record;
    }

    //编辑记录方法
    public function editUser($recordId) {
        if(true == $this->verifyIsAdmin($recordId)) {
            if($_SESSION['userId'] != $recordId) {
                LittleTools::alertAndExit('您没有权限修改此用户信息！');
            }
        }
        if(false === $this->uploadFile()) {
            return $this->_error->getErrorInfo();
        }
        if(isset($_POST['del_image'])) {
            if(!empty($_POST['del_image'])) {
                if(false === $this->deleteFile($_POST['old_image_path'])) {
                    Logger::log('删除文件失败！' . $_POST['old_image_path']);
                } else {
                    $_POST['image_path']= '';
                }
            } else {
                $_POST['image_path']    = $_POST['old_image_path'];
            }
        }
        if(empty($_POST['edit_password'])) {
            $data['user_id']  = $_POST['user_id'];
            $data['sort_loc']   = $_POST['sort_loc'];
            $data['user_desc']  = $_POST['user_desc'];
            $data['image_path']  = $_POST['image_path'];
        } else {
            $data   = $this->create();
            if(false === $data) {
                return $this->getError();
            }
        }
        if(false === $this->save($data)) {
            return $this->getError();
        }

        return true;
    }

    //添加记录方法
    public function addUser() {
        if(false === $this->uploadFile()) {
            return $this->_error->getErrorInfo();
        }
        if(false === $this->create()) {
            return $this->getError();
        }
        if(false === $this->add()) {
            return false;
            return $this->getError();
        }

        return true;
    }

    //删除记录方法
    public function deleteUser($recordId) {
        if(true == $this->verifyIsSelf($recordId)) {
            LittleTools::alertAndExit('不能删除自己！');
        }
        if(true === $this->verifyIsAdmin($recordId)) {
            LittleTools::alertAndExit('Admin是超级管理员不能删除！');
        }
        
        return $this->quickDeleteUser(array($recordId));
    }

    //验证是否是超级管理员
    public function verifyIsAdmin($recordId) {
        $admin  = $this->where('`user_name` = \'admin\'')->getField('`user_id`'); 
        if(is_array($recordId) && in_array($admin['user_id'], $recordId)) {
            return true;
        }
        if($recordId == $admin['user_id']) {
            return true;
        }

        return false;
    }

    //看一下删除中是否包含有自己
    public function verifyIsSelf($recordId) {
        if(is_array($recordId) && in_array($_SESSION['userId'], $recordId)) {
            return true;
        }
        if($recordId == $_SESSION['userId']) {
            return true;
        }

        return false;

    }

    //快捷操作：删除记录
    public function quickDeleteUser(array $recordIds){
        if(true == $this->verifyIsSelf($recordId)) {
            LittleTools::alertAndExit('不能删除自己！');
        }
        if(true === $this->verifyIsAdmin($recordId)) {
            LittleTools::alertAndExit('Admin是超级管理员不能删除！');
        }
        $this->quickDeleteImageUser($recordIds);
        $whereStr   = $this->genWhereIn('user_id', $recordIds);
        
        return $this->where($whereStr)->delete();
    }

    //快捷操作：删除记录相关文件
    public function quickDeleteImageUser(array $recordIds) {
        $whereStr   = $this->genWhereIn('user_id', $recordIds) . ' AND (`image_path` !=\'\' AND `image_path` IS NOT NULL)';
        $recordList = $this->where($whereStr)->field('user_id, image_path')->select();
        if(empty($recordList)) {
            return ture;
        }
        $whereStr   = '`user_id` IN (';
        foreach($recordList as $record) {
            if($this->deleteFile($record['image_path'])) {
                $whereStr   .= $record['user_id'] . ', ';
            }
        }
        $whereStr    .= '-1)'; 

        return $this->where($whereStr)->setField('image_path', '');
    }

    //用户登陆验证
    public function verifyUser($userName, $userPassword) {
        $userPassword   = md5($userPassword);
        $whereStr   = '`user_name` = \'' . $userName .
                      '\' AND `user_password` = \'' . $userPassword . '\'';
        $record     = $this->where($whereStr)->find();
        if(empty($record)) {
            return false;
        }

        return $record;
    }

    //生成WhereIn条件语句
    protected function genWhereIn($field, array $values) {
        return '`' . $field . '` IN (' . implode(',', $values) . ', -1)';
    }

    //上传文件方法
    protected function uploadFile() {
        if(!empty($_FILES['image_path']['name'])) {
            $uploadFile     = new UploadFile($_FILES['image_path'],
                                        $this->_uploadDir,
                                        $this->_imageTypes,
                                        $this->_imageSize);
            if(false === $uploadFile->upload()) {
                $this->_error->setErrorInfo($uploadFile->getError());
                return false;
            }
            $arrPath    = explode('/', $uploadFile->getUploadFilePath());
            $_POST['image_path']    = array_pop($arrPath);
            $_POST['image_path']    = array_pop($arrPath) . '/' . $_POST['image_path'];
            //生成缩略图
            $this->genThumbImage($uploadFile->getUploadFilePath());
            
            return true;
        }

        return true;
    }

    //生成缩略图
    protected function genThumbImage($srcFilePath) {
        $thumbImgName  = $this->genThumbImageName($srcFilePath);
        foreach(self::$thumbImgInfo as $kind => $thumbInfo) {
            $thumbImgPath   = $thumbImgName . $kind . '.' . $thumbInfo['t'];
            $genResult      = Image::thumb($srcFilePath, $thumbImgPath, $thumbInfo['t'], $thumbInfo['w'], $thumbInfo['h'], $thumbInfo['i']);
            if(!$genResult) {
               //log 
            }
        } 
    }

    //得到缩略图的路径及文件名
    public function genThumbImageName($srcFilePath) {
        return mb_substr($srcFilePath , 0, strrpos($srcFilePath, '.'), 'utf-8');
    }

    //这个将会作为一个interface
    protected function deleteFile($filePath) {
        if(!empty($filePath)) {
            $this->delThumbImageFile($filePath);
            return LittleTools::deleteFile($filePath, $this->_uploadDir);
        }

        return true;
    }

    //删除相关缩略图
    protected function delThumbImageFile($filePath) {
        $thumbImgName  = $this->genThumbImageName($filePath);
        foreach(self::$thumbImgInfo as $kind => $thumbInfo) {
            $thumbImgPath   = $thumbImgName . $kind . '.' . $thumbInfo['t'];
            LittleTools::deleteFile($thumbImgPath, $this->_uploadDir);
        } 
    }

    public function getUploadDir() {
        return preg_replace('/public/i', '', $this->_uploadDir);
    }

}

?>
